package com.maimao.order.controller;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.maimao.core.model.auth.AuthUser;
import com.maimao.core.model.resp.Result;
import com.maimao.core.utils.DateUtils;
import com.maimao.model.order.input.OrderSearchInput;
import com.maimao.model.order.vo.ExportOrderEntity;
import com.maimao.model.user.Shop;
import com.maimao.order.client.ShopClient;
import com.maimao.order.controller.base.BaseController;
import com.maimao.order.serivce.OrderService;
import com.maimao.utils.excel.ExcelUtil;
import com.maimao.utils.excel.convert.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.stream.Collectors;

import static com.maimao.core.constant.AuthKey.COMPANY;
import static com.maimao.core.constant.AuthKey.MEMBER;
import static com.maimao.core.constant.Constants.UNDER_LINE;

/**
 * @author MaoLin Wang
 * @date 2021/4/28 下午2:19
 */
@RestController
@Slf4j
@RequestMapping("/excel")
public class ExcelController extends BaseController {

    public static final String ORDER_EXPORT_PATH = "/Users/wangmaolin/IdeaProjects/maimao/maimao_server/maimao_parent/maimao_order/src/main/resources/excel/export/{}/";
    @Autowired
    private OrderService orderService;

    @Autowired
    private ShopClient shopClient;

    @Autowired
    private ThreadPoolTaskExecutor excelExportExecutor;

    /**
     * 导出订单
     *
     * @param input 过滤条件
     */
    @PostMapping("/export")
    public void export(@RequestBody OrderSearchInput input,
                       @RequestParam(value = "page", defaultValue = "1") Integer page,
                       @RequestParam(value = "size", defaultValue = "5") Integer size) throws IOException {
        AuthUser authUser = checkAndGetAuthUser();
        if (input.isShopOrder()) {
            Result<Void> x = setShopId(input, authUser);
            if (x != null) {
                throw new RuntimeException("尚未开通店铺");
            }
        }
        if (input.isUserOrder()) {
            input.setUserId(authUser.getId());
        }
        final HttpServletResponse response = getResponse();
        List<ExportOrderEntity> exportDatas = orderService.export(input, page, size);
        if (ObjectUtil.isNotEmpty(exportDatas)) {
            exportDatas = exportDatas.stream().sorted(Comparator.comparing(ExportOrderEntity::getCreateTime).reversed()).collect(Collectors.toList());
        }
        ExcelUtil excelUtil = null;
        try {
            excelUtil = ExcelUtil.builder().setMustParams(ExportOrderEntity.class, exportDatas, authUser.getUsername() + UNDER_LINE + "order", response)
                    .setMergeColumns(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22)
                    .setConverts(new ShippedStatusConvert(),new CommonBoolConvert(),new OrderStatusConvert(),new OrderShopStatusConvert(),new OrderTypeConvert());
            Map<Integer, Set<Integer>> mergeUpToMap = Maps.newHashMapWithExpectedSize(3);
            mergeUpToMap.put(0, Sets.newHashSet(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22));
            mergeUpToMap.put(13, Sets.newHashSet(14, 15, 16, 17, 18, 19, 20, 21, 22));
            excelUtil.exportWithMerge(mergeUpToMap);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("导出excel失败{}", input);
            try {
                getResponse().getWriter().print(Result.fail("导出失败"));
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        }
        ExcelUtil finalExcelUtil = excelUtil;
        excelExportExecutor.submit(() -> {

            try {
                finalExcelUtil.exportToLocal(StrUtil.format(ORDER_EXPORT_PATH, DateUtils.todayStr()));
            } catch (IOException e) {
                e.printStackTrace();
                log.error("导出excel到本地失败");
            }


        });

    }

    private Result setShopId(@RequestBody OrderSearchInput input, AuthUser authUser) {
        Result<Shop> shopRes = null;
        if (authUser.getRole().equals(COMPANY)) {
            //企业用户
            shopRes = shopClient.findShopByOwner(authUser.getId2Long(), 1);
        } else if (authUser.getRole().equals(MEMBER)) {
            //普通用户
            shopRes = shopClient.findShopByOwner(authUser.getId2Long(), 0);
        } else {
            return Result.notValid("非法用户");
        }
        if (shopRes == null || shopRes.getData() == null || shopRes.getData().getId() == null || shopRes.getData().getId() <= 0) {
            return Result.notValid("您尚未开通店铺");
        }
        input.setShopId(shopRes.getData().getId());
        return null;
    }
}
